package com.decent.ejfadmin.config;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.util.Date;

/**
 * 配置文件实体类
 *
 * @author 陈豆豆
 */
@Configuration
@PropertySource(value = "classpath:oss-config.properties")
@Getter
@Component
public class OssConfig {
    /**
     * 阿里云账号id
     */
    @Value("${access_key_id}")
    private String accessKeyId;
    /**
     * 阿里云账号密钥
     */
    @Value("${access_key_secret}")
    private String accessKeySecret;
    /**
     * 对象存储oss外网endpoint
     */
    @Value("${end_point}")
    private String endPoint;
    /**
     * 存储空间
     */
    @Value("${bucket_name}")
    private String bucketName;
    /**
     * 阿里云OSS客户端
     */
    private OSSClient ossClient;

    public OSSClient getOssClient() {
        if (ossClient == null) {
            ossClient = new OSSClient(endPoint, new DefaultCredentialProvider(accessKeyId, accessKeySecret), null);
        }
        return ossClient;
    }

    /**
     * 生成图片返显url
     *
     * @param picKey     图片key
     * @param expiration 过期时间
     * @return url
     */
    public String getPicUrl(String picKey, Date expiration) {
        GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, picKey, HttpMethod.GET);
        req.setExpiration(expiration);
        URL signedUrl = this.getOssClient().generatePresignedUrl(req);
        return signedUrl.toString();
    }
}
